<template>
  <div class="project-details">
    <div class="header">
      <div class="project-details-title">ICT项目交付详情</div>
      <div class="button-group">
        <el-button
          @click="initiateProjectChange"
          type="warning"
          v-if = "projectChangeable"
        >发起变更</el-button>
      </div>
    </div>
    <el-steps class="mt-24 mb-24 plr-96" :active="currentProcessStageStepIndex" align-center>
      <el-step
        v-for="(step, index) in computedStepList" 
        :key="index" 
        :title="step.name"
        :class="{ 'is-selected': index === activeStepIndex }"
        @click.enter="handleStepClick(step.name, index)"/>
    </el-steps>
    <div class="flex">
      <div style="flex: 1; min-width: 0;">
        <!-- 项目基本信息 -->
        <div class="desc-item">
          <div class="form-item">项目基本信息</div>
          <DynamicDescription
            :descriptions="projectDetails.projectBasicDescs"
            :readOnly="true"
            :column="2"
          />
        </div>
        
        <ProjectTransfer
          v-if="projectInfoLoaded && processStageName==='项目移交'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :projectTransferDetails="projectTransferDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <ProjectGrading
          v-if="projectInfoLoaded && processStageName==='项目定级'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :projectGradingDetails="projectGradingDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <TeamFormation
          v-if="projectInfoLoaded && processStageName==='团队组建'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :teamFormationDetails="teamFormationDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <StartupReporting
          v-if="projectInfoLoaded && processStageName==='项目开工'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :startupReportingDetails="startupReportingDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <ExecuteProgress
          v-if="projectInfoLoaded && processStageName==='实施进度'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :executeProgressDetails="executeProgressDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <TestRun
          v-if="projectInfoLoaded && processStageName==='试运行'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :testRunDetails="testRunDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <ProjectDelivery
          v-if="projectInfoLoaded && processStageName==='项目交付'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :projectDeliveryDetails="projectDeliveryDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <ProjectAudit
          v-if="projectInfoLoaded && processStageName==='项目审计'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :projectAuditDetails="projectAuditDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <ProjectReview
          v-if="projectInfoLoaded && processStageName==='后评估'"
          :isShowApprovalOperation="isShowApprovalOperation"
          :projectInfo="projectInfo"
          :projectReviewDetails="projectReviewDetails"
          :processStageName="processStageName"
          :taskName="taskName"
          :role="role"
          :processList="processList"
          :projectFiles="projectFiles"
          @getApprovalProcess="getApprovalProcess"
          @getProjectInfo="getProjectInfo"
          @getProjectFilesInfo="getProjectFilesInfo"
        />

        <!-- 项目信息 -->
        <div class="desc-item">
          <div class="form-item">项目详情信息</div>
          <el-tabs 
            v-model="tabPosition" 
            class="custom-tabs"
            :stretch="true">
            <el-tab-pane label="基本信息" name="1" />
            <el-tab-pane label="财务信息" name="2" />
            <el-tab-pane label="合同信息" name="3" />
            <el-tab-pane label="客户信息" name="4" />
            <el-tab-pane label="交付团队信息" name="5" />
            <el-tab-pane label="关键人信息" name="6" />
            <el-tab-pane label="采购信息" name="7" />
            <!-- <el-tab-pane label="其他" name="7" /> -->
            <el-tab-pane label="变更记录" name="8" />
            <el-tab-pane
              v-if="projectInfo.ictSupplementInfo && projectInfo.ictSupplementInfo.length > 0"
              label="ICT补充信息"
              name="10"
            />
            <el-tab-pane label="附件" name="9" />
          </el-tabs>
          <!-- 基本信息 -->
          <DynamicDescription
            v-if="tabPosition === '1'"
            :descriptions="projectDetails.basicInfoDescs"
            :readOnly="true"
            :column="2"
          />
          <!-- 财务信息 -->
          <DynamicDescription
            v-if="tabPosition === '2'"
            :descriptions="projectDetails.financeDescs"
            :readOnly="true"
            :column="2"
          />
          <!-- 合同信息 -->
          <DynamicDescription
            v-if="tabPosition === '3'"
            :descriptions="projectDetails.contractDescs"
            :readOnly="true"
            :column="2"
          />
          <!-- 客户信息 -->
          <DynamicDescription
            v-if="tabPosition === '4'"
            :descriptions="projectDetails.customerDescs"
            :readOnly="true"
            :column="2"
          />
          <!-- 交付团队信息 -->
          <DynamicDescription
            v-if="tabPosition === '5'"
            :descriptions="projectDetails.teamDescs"
            :readOnly="true"
            :column="2"
          />
          <div v-if="tabPosition === '5'">
            <div class="table-title">团队成员</div>
            <el-table
              :data="projectDetails.membersTableData"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              style="width: 100%">
              <el-table-column prop="user_name" label="姓名"/>
              <el-table-column prop="contact_information" label="联系电话"/>
              <!-- 合并部门和公司显示在一列 -->
              <el-table-column
                label="部门 / 公司"
                :formatter="row => `${row.department_name} ${row.company}`"
              />
              <!-- 格式化加入日期，只显示日期部分 -->
              <el-table-column
                prop="joining_date"
                label="加入日期"
                :formatter="row => formatDate(row.joining_date, 'YYYY-MM-DD')"
              />
            </el-table>
          </div>
          <!-- 关键人信息 -->
          <div v-if="tabPosition === '6'">
            <div class="table-title">项目关键人员</div>
            <el-table
              :data="projectDetails.keyPersonTableData"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              style="width: 100%">
              <el-table-column prop="role" label="角色"/>
              <el-table-column prop="name" label="姓名"/>
              <el-table-column prop="work_no" label="工号"/>
              <el-table-column prop="phone" label="联系电话"/>
            </el-table>
          </div>
          <!-- 采购信息 -->
          <div v-if="tabPosition === '7'">
            <div class="table-title">项目采购信息</div>
            <el-table
              :data="projectDetails.purchaseDescs"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              style="width: 100%">
              <el-table-column prop="source_type" label="采购类型"/>
              <el-table-column prop="status" label="采购状态"/>
              <el-table-column prop="add_user" label="项目经理"/>
              <el-table-column prop="add_user_phone" label="项目经理联系方式"/>
              <el-table-column prop="apply_time" label="采购时间"/>
              <el-table-column prop="cooperator_si" label="合作商名称"/>
              <el-table-column prop="factory_bid_amount_contain_tax" label="采购厂家中标金额（含税，元）"/>
              <el-table-column prop="factory_bid_amount_no_tax" label="采购厂家中标金额（不含税，元）"/>
              <el-table-column prop="purchase_no" label="Epms采购单号"/>
            </el-table>
          </div>
          <!-- 变更记录 -->
          <div v-if="tabPosition === '8'">
            <ProjectChangeList
              :projectCode="projectCode"
            />
          </div>
          <!-- ICT售前补充信息 -->
          <DynamicDescription
            v-if="tabPosition === '10'"
            :descriptions="projectDetails.ictSupplementDescs"
            :readOnly="true"
            :column="2"
          />
          <!-- 附件 -->
          <div v-if="tabPosition === '9'">
            <FilesList
              :projectDetails="projectDetails"
              :fileIconObj="fileIconObj"
              :previewableTypes="previewableTypes"
              :projectFiles="projectShowFiles"
            />
          </div>
        </div>
      </div>
      <!-- 审批流程 -->
      <div class="timeline">
        <el-timeline style="max-width: 600px; min-width: 200px;">
          <el-timeline-item
            v-for="(process, index) in processList"
            :key="index"
            :color="approvalFontColor[process.status]"
            placement="top"
          >
            <slot name="timestamp">
              <div class="timeline-title">
                {{ process.name }}
                <el-tag color="#ecf5ff" :style="{ color: approvalFontColor[process.status] }">{{
                  approvalStatusObj[process.status]
                }}</el-tag>
              </div>
            </slot>
            <el-card>
              <p>处理人：{{ process.assignee_user.nickname }}</p>
              <p>创建时间：{{ formatDate(process.create_time) }}</p>
              <p>审批时间：{{ formatDate(process.end_time) }}</p>
              <p>审批意见：{{ process.reason }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import { staticData } from '@/views/project/mixins/staticDataMixin'
import { descriptionFileds } from '@/views/project/projectDetails/mixins/projectDetailsMixin'
import { projectTranferDescriptionFileds } from '@/views/project/projectDetails/mixins/projectTransferDetailsMixin'
import { projectGradingDescriptionFileds } from '@/views/project/projectDetails/mixins/projectGradingDetailsMixin'
import { projectAuditDescriptionFileds } from '@/views/project/projectDetails/mixins/projectAuditDetailsMixin'
import { teamFormationDescriptionFileds } from '@/views/project/projectDetails/mixins/teamFormationDetailsMixin'
import { startupReportingDescriptionFileds } from '@/views/project/projectDetails/mixins/startupReportingDetailsMixin'
import { executeProgressDescriptionFileds } from '@/views/project/projectDetails/mixins/executeProgressDetailsMixin'
import { testRunDescriptionFileds } from '@/views/project/projectDetails/mixins/testRunDetailsMixin'
import { projectDeliveryDescriptionFileds } from '@/views/project/projectDetails/mixins/projectDeliveryDetailsMixin'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import FilesList from '@/views/project/projectDetails/components/FilesList.vue'
import ProjectChangeList from '@/views/project/projectDetails/components/ProjectChangeList.vue'
import ProjectTransfer from '@/views/project/projectDetails/components/ProjectTransfer.vue'
import ProjectGrading from '@/views/project/projectDetails/components/ProjectGrading.vue'
import ProjectAudit from '@/views/project/projectDetails/components/ProjectAudit.vue'
import TeamFormation from '@/views/project/projectDetails/components/TeamFormation.vue'
import StartupReporting from '@/views/project/projectDetails/components/StartupReporting.vue'
import ExecuteProgress from '@/views/project/projectDetails/components/ExecuteProgress.vue'
import TestRun from '@/views/project/projectDetails/components/TestRun.vue'
import ProjectDelivery from '@/views/project/projectDetails/components/ProjectDelivery.vue'
import ProjectReview from '@/views/project/projectDetails/components/ProjectReview.vue'
import { formatDate} from '@/utils/formatTime'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { useRouter } from 'vue-router'

onBeforeMount(async () => {
  await getProjectInfo()// 先加载项目信息
  await getProjectStageInfo()
  await getApprovalProcess()
  // getProjectInfo()
  setRole()
})
  
// data
// 路由
const router = useRouter()
// 获取当前登录用户
const { wsCache } = useCache()
const currentUser = wsCache.get(CACHE_KEY.USER).user
// 静态变量
const {processConfig, stepList, approvalStatusObj, approvalFontColor, fileIconObj, previewableTypes, constructionProjectFiles, constructionProjectShowFiles, maintenanceProjectFiles, maintenanceProjectShowFiles} = staticData()

// 纯运维项目不显示中间环节
const constructionMode = ref('')
const computedStepList = computed(() => {
  // if (constructionMode.value == '纯运维') {
  //   return [
  //     { name: '项目移交' },
  //     { name: '项目交付' },
  //     // { name: '项目审计' },
  //     { name: '后评估' }
  //   ]
  // }
  return stepList
})

const projectFiles = computed(() => {
  if (constructionMode.value == '纯运维') {
    return maintenanceProjectFiles
  }
  return constructionProjectFiles
})

const projectShowFiles = computed(() => {
  if (constructionMode.value == '纯运维') {
    return maintenanceProjectShowFiles
  }
  return constructionProjectShowFiles
})

// 流程列表
let processList = ref([])
// 项目信息
let projectInfo = reactive({})
const projectInfoLoaded = ref(false)

const route = useRoute()

const projectDetails = reactive({
  // 项目基本信息
  projectBasicDescs: [],
  // 项目详情信息
  // 基本信息
  basicInfoDescs: [],
  // 财务信息
  financeDescs: [],
  // 合同信息
  contractDescs: [],
  // 客户信息
  customerDescs: [],
  // 交付团队信息
  teamDescs: [],
  // 关键人信息
  keyPersonTableData: [],
  // 采购信息
  purchaseDescs: [],
  // 其他
  otherDescs: [],
  // 团队成员信息
  membersTableData: [],
  // 附件信息
  filesTableData: [],
  // ICT售前补充信息
  ictSupplementDescs: []
})

const projectTransferDetails = reactive({
  // 项目接收信息
  projectAcceptDesc: [],
  projectAcceptForm: {},
  // 选择交付经理信息
  projectManagerDesc: [],
  projectManagerForm: {},
  // 项目流程信息
  projectProcessDescs: [],
  projectProcessForm: {},
})

// 项目定级信息
const projectGradingDetails = reactive({
  preProjectGradingInfoDesc: [],
  projectGradingInfoDesc: [],
  projectGradingInfoForm: {},
  autonomousAbilityDesc: {},
  projectGradingSecondInfoDesc: []
})

// 团队组建信息
const teamFormationDetails = reactive({
  teamFormationInfoDesc: [],
  teamFormationInfoForm: {},
})

// 项目开工信息
const startupReportingDetails = reactive({
  startupReportingInfoDesc: [],
  startupReportingInfoForm: {},
  startupReportingSecondInfoDesc: [],
  startupReportingThirdInfoDesc: []
})

// 实施进度信息
const executeProgressDetails = reactive({
  executeProgressInfoDesc: [],
  executeProgressInfoForm: {},
  executeProgressSecondInfoDesc: []
})

// 试运行信息
const testRunDetails = reactive({
  testRunInfoDesc: [],
  testRunInfoForm: {},
  testRunSecondInfoDesc: []
})

// 项目交付
const projectDeliveryDetails = reactive({
  projectDeliveryInfoDesc: [],
  projectDeliveryInfoForm: {},
  projectDeliverySecondInfoDesc: [],
  projectDeliveryThirdInfoDesc: [],
  projectDeliveryFourthInfoDesc: [],
  projectDeliverySixthInfoDesc: []
})

// 项目审计
const projectAuditDetails = reactive({
  projectAuditInfoDesc: [],
  projectAuditInfoForm: {},
})

// 后评估
const projectReviewDetails = reactive({
  projectReviewInfoDesc: [],
  projectReviewInfoForm: {},
})


const role = ref('')
// 项目详情tab参数
const tabPosition = ref('1')

const projectCode = route.query.project_code
const currentProcessInstanceId = ref()
const projectStageInfo = ref([])
const processStageName = ref()
const currentProcessStageName = ref()
const taskName = ref()
// 当前活跃的步骤索引
const activeStepIndex = ref(-1)
// 当前最新流程对应的步骤索引
const currentProcessStageStepIndex = ref(0)

const projectChangeable = computed(() => {
  // 如果依赖项还未初始化，返回 false
  if (
    processStageName.value === undefined ||
    currentUser.id === undefined ||
    projectInfo.construction_project_manager_id === undefined
  ) {
    return false
  }
  
  // 如果项目已完成，也可发起变更
  // if(projectInfo.finished) {
  //   return true
  // }

  // 否则计算逻辑
  return processStageName.value !== '项目移交' && currentUser.id == projectInfo.construction_project_manager_id
})

// 处理步骤条点击事件
const handleStepClick = (stepName: string, index: number) => {
  // 查找第一个匹配的流程实例
  const processInstance = projectStageInfo.value.find(process => process.name === stepName);
  if (processInstance) {
    // 更新当前流程阶段名，这将触发组件的显示更新
    processStageName.value = stepName;
    // 更新活跃的步骤索引
    activeStepIndex.value = index
      // 移除所有节点的 is-selected 类
    document.querySelectorAll('.el-step__head').forEach(el => {
      el.classList.remove('is-selected');
    });
    
    // 为选中的节点添加 is-selected 类
    const selectedStep = document.querySelector(`.el-step:nth-child(${index + 1}) .el-step__head`);
    if (selectedStep) {
      selectedStep.classList.add('is-selected');
    }
    getApprovalProcess(processInstance.id)
    getProjectInfo()
  }
};

const setRole = () => {
  const stage = processStageName.value;
  const task = taskName.value;
  
  // 检查当前阶段是否存在
  if (processConfig[stage]) {
    // 查找当前任务
    const taskConfig = processConfig[stage].find(item => item.task === task);
    if (taskConfig) {
      role.value = taskConfig.role;
    }
  }
};

// methods
// 只读判断，是否展示审批按钮，控制不同流程操作按钮展示
const isShowApprovalOperation = (currentProcess) => {
  const stage = processStageName.value;
  const task = taskName.value;
  
  if (stage && processConfig[stage]) {
    // 注意：currentProcess 是从 1 开始的索引，数组索引从 0 开始
    const index = parseInt(currentProcess.replace('first', '0')
      .replace('second', '1')
      .replace('third', '2')
      .replace('fourth', '3')
      .replace('fifth', '4')
      .replace('sixth', '5')
      .replace('seventh', '6'));
    
    if (index >= 0 && index < processConfig[stage].length) {
      const taskConfig = processConfig[stage][index];
      
      if (task === taskConfig.task && role.value === taskConfig.role) {
        const process = processList.value.filter((p) => p.name === task)[0];
        if (currentUser.id === process?.assignee_user.id && [0, 1].includes(process?.status)) {
          return true;
        }
      }
    }
  }
  
  return false;
};

// 获取项目文件信息
const getProjectFilesInfo = async () => {
  const params = {
    project_code: projectCode
  }

  const docRes = await KmsApi.getProjectDocInfo(params)
  projectInfo.files = docRes || []
}

// 获取项目基本信息
const getProjectInfo = async () => {
  const params = {
    project_code: projectCode
  }
  
  try {
    // 获取项目基本信息
    const res = await KmsApi.getProjectInfo(params)
    projectInfoLoaded.value = false
    Object.assign(projectInfo, res)

    if (projectInfo.construction_mode == '纯运维') {
      constructionMode.value = '纯运维'
    }

    if(projectInfo.finished) {
      currentProcessStageStepIndex.value = computedStepList.value.length
    }
    
    // 并行获取其他相关信息，使用 Promise.allSettled 代替 Promise.all
    const results = await Promise.allSettled([
      KmsApi.getProjectPurchaseInfo(params),
      KmsApi.getProjectDocInfo(params),
      KmsApi.getTeamMembersInfo(params),
      KmsApi.getExecuteProgressInfo(params),
      KmsApi.getReviewInfo(params),
      KmsApi.getIctSupplementInfo(params)
    ])

    // 处理各个请求的结果
    const [purchaseRes, docRes, membersRes, progressRes, reviewRes, ictSupplementRes] = results.map(result => 
      result.status === 'fulfilled' ? result.value : (console.error('请求失败:', result.reason), null)
    )

    // 填充获取到的数据，每个都进行空值检查
    projectInfo.purchase = purchaseRes || []
    projectInfo.files = docRes || []
    projectInfo.members = membersRes || []
    projectInfo.progress = progressRes || []
    projectInfo.reviewInfo = reviewRes || []
    projectInfo.ictSupplementInfo = ictSupplementRes || []

    // 对 membersRes 进行特殊处理，确保即使为 null 也不会报错
    const safeMembers = membersRes || {}
    const partnerList = safeMembers.partner || []
    const teamMembersList = safeMembers.teamMembers || []

    // 更新各模块详情信息
    // 项目基本信息
    Object.assign(projectDetails, reactive(descriptionFileds(projectInfo)))
    // 项目基本信息的团队成员信息
    projectDetails.membersTableData = partnerList.concat(teamMembersList)
    // 项目移交信息
    Object.assign(projectTransferDetails, reactive(projectTranferDescriptionFileds(projectInfo)))
    // 项目定级信息
    Object.assign(projectGradingDetails, reactive(projectGradingDescriptionFileds(projectInfo)))
    // 团队组建信息
    Object.assign(teamFormationDetails, reactive(teamFormationDescriptionFileds(projectInfo)))
    // 开通填报信息
    Object.assign(startupReportingDetails, reactive(startupReportingDescriptionFileds(projectInfo)))
    // 实施进度信息
    Object.assign(executeProgressDetails, reactive(executeProgressDescriptionFileds(projectInfo)))
    // 试运行信息
    Object.assign(testRunDetails, reactive(testRunDescriptionFileds(projectInfo)))
    // 项目交付信息
    Object.assign(projectDeliveryDetails, reactive(projectDeliveryDescriptionFileds(projectInfo)))

    
    projectInfoLoaded.value = true
    // projectChangeable.value = processStageName.value !== '项目移交' && currentUser.id == projectInfo.construction_project_manager_id

    // 获取关键人信息
    const userIdList = projectDetails.keyPersonTableData
      .filter(person => person.id)
      .map(person => parseInt(person.id, 10));

    const userIdListData = { user_id_list: userIdList };
    try {
      // 发送请求获取keyPersonsRes
      const keyPersonsRes = await IctApi.getKeyPersons(userIdListData);
      // 使用keyPersonsRes补充projectDetails.keyPersonTableData的数据
      projectDetails.keyPersonTableData.forEach(person => {
        const matchedPerson = keyPersonsRes.find(res => res.id.toString() === person.id);
        if (matchedPerson) {
          person.phone = matchedPerson.phone;
          person.work_no = matchedPerson.work_no;
        }
      });
    } catch (error) {
      console.error("获取关键人信息失败:", error);
    }
    
  } catch (error) {
    console.error('项目基本信息获取错误:', error)
    projectInfoLoaded.value = true  // 确保出错时也设置加载完成
  }
}

// 获取审批流程信息
const getApprovalProcess = async (processInstanceId = currentProcessInstanceId.value) => {
  const params = {
    processInstanceId: processInstanceId
  }
  await BpmApi.getApprovalProcessList(params).then((res) => {
    processList.value = res
    taskName.value = processList.value[0].name
  })
}


const getProjectStageInfo = async () => {
  const params = {
    project_code_list: [projectCode]
  }
  
  await BpmApi.getProjectStage(params).then(res => {
    projectStageInfo.value = res[projectCode as string]
    processStageName.value = projectStageInfo.value[0].name
    currentProcessStageName.value = projectStageInfo.value[0].name
    currentProcessInstanceId.value = projectStageInfo.value[0].id
    // currentProcessStageStepIndex.value = stepList.findIndex(step => step.name === currentProcessStageName.value)
    // if (constructionMode.value == '纯运维') {
    //   currentProcessStageStepIndex.value = [
    //     { name: '项目移交' },
    //     { name: '项目交付' },
    //     // { name: '项目审计' },
    //     { name: '后评估' }
    //   ].findIndex((step) => step.name === currentProcessStageName.value)
    // } else {
    //   currentProcessStageStepIndex.value = stepList.findIndex(
    //     (step) => step.name === currentProcessStageName.value
    //   )
    // }
    currentProcessStageStepIndex.value = stepList.findIndex(
        (step) => step.name === currentProcessStageName.value
      )

    if(projectInfo.finished) {
      currentProcessStageStepIndex.value = computedStepList.value.length
    }

    activeStepIndex.value = currentProcessStageStepIndex.value
  })
}

function initiateProjectChange() {
  router.push({
    name: 'ProjectChange',
    query: {
      project_code: projectInfo.project_code
    }
  })
}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

.project-details {
  width: 100%;

  &-title {
    text-align: center;
    font-weight: 600;
    font-size: 24px;
  }
  .timeline {
    background: #ffffff;
    box-shadow: 0px 0px 10px 0px #dbdbdb;
    margin-left: 16px;
    padding: 16px 24px;
    overflow: auto;
    .timeline-title {
      align-items: center;
      font-weight: 600;
      padding-bottom: 4px;
    }
  }
}

// 步骤条样式复写
::v-deep .el-step__head {
  &.is-finish,
  &.is-process {
    border-color: #67c23a;
    .el-step__icon {
      cursor: pointer;
      transition: transform 0.3s ease;
      width: 36px;
      height: 36px;
      color: #e9f0fd;
      border: none;
      position: relative;
      overflow: visible;

      &:hover {
        transform: scale(1.1);
      }

      &::after {
        content: '';
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        border-radius: 50%;
        opacity: 0;
        transform: scale(1);
        pointer-events: none;
      }

      &:active::after {
        animation: ripple 1.2s cubic-bezier(0.25, 0.8, 0.25, 1);
      }
    }
  }

  .el-step__line {
    cursor: default;
    pointer-events: none;
  }
}

::v-deep .el-step__head.is-finish {
  .el-step__icon {
    background: #67c23a;

    &::after {
      background: rgba(103, 194, 58, 0.6); // 完成状态的扩散效果颜色
    }
  }
  .el-step__line {
    top: 18px;
    background: #67c23a;
  }
}

::v-deep .el-step__head.is-process {
  .el-step__icon {
    background: #1278e8;
    animation: breathe 2s infinite ease-in-out;

    &::before {
      content: '';
      position: absolute;
      top: -4px;
      left: -4px;
      right: -4px;
      bottom: -4px;
      border-radius: 50%;
      background: rgba(18, 120, 232, 0.3);
      animation: pulse 2s infinite ease-in-out;
    }

    &::after {
      background: rgba(18, 120, 232, 0.6); // 进行中状态的扩散效果颜色
    }
  }
  .el-step__line {
    top: 18px;
    background: #cfe0f2;
  }
}

::v-deep .el-step__head.is-wait {
  .el-step__icon {
    cursor: default;
    width: 36px;
    height: 36px;
    background: #cfe0f2;
    color: #e9f0fd;
    border: none;
  }
  .el-step__line {
    top: 18px;
    background: #cfe0f2;
  }
}

::v-deep .el-step__icon-inner {
  font-size: 15px;
  color: #ffffff;
}

::v-deep .el-step__title {
  color: #000000 !important;
  font-weight: 600;
  font-size: 15px;
}

// 时间线样式复写
::v-deep .el-timeline {
  padding: 0;
}

::v-deep .el-timeline-item__wrapper {
  top: -15px;
}

// 呼吸动画
@keyframes breathe {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

// 光圈扩散动画
@keyframes ripple {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  25% {
    transform: scale(1.2);
    opacity: 0.75;
  }
  50% {
    transform: scale(1.3);
    opacity: 0.5;
  }
  75% {
    transform: scale(1.4);
    opacity: 0.25;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

// 持续光圈动画
@keyframes pulse {
  0%, 100% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 0.3;
    transform: scale(1.2);
  }
}

// 更新选中状态样式
::v-deep .el-step.is-selected {
  .el-step__head.is-finish {
    .el-step__icon {
      background: #7fd63e; // 稍微亮一点的绿色
      box-shadow: 0 0 0 3px rgba(127, 214, 62, 0.3),
                  0 0 8px rgba(127, 214, 62, 0.5);
      transform: scale(1.08);
    }
  }
  .el-step__head.is-process {
    .el-step__icon {
      background: #3c8ce7; // 稍微亮一点的蓝色
      box-shadow: 0 0 0 3px rgba(60, 140, 231, 0.3),
                  0 0 8px rgba(60, 140, 231, 0.5);
      transform: scale(1.08);
    }
  }
  .el-step__title {
    color: #3c8ce7 !important; // 更改标题颜色以匹配选中状态
    font-weight: 800; // 稍微加粗标题
    font-size: 16px;
  }
}

.header {
  position: relative;
  display: flex;
  justify-content: center; /* 使标题居中 */
  align-items: center;
}

.project-details-title {
  text-align: center;
  flex: 1; /* 让标题占据剩余空间 */
}

.button-group {
  position: absolute; /* 使用绝对定位 */
  right: 0; /* 让按钮组靠右 */
  margin-left: auto; /* 确保按钮在右侧 */
  margin-bottom: 4px; /* 适当的底部间距 */

  .el-button {
    margin-left: 4px;
  }
}

.custom-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 0px;
}

.custom-tabs :deep(.el-tabs__item) {
  padding: 0 10px !important; /* 减小tab之间的间距 */

}
</style>